<!-- 页面标注 -->
<html>

<head>
	<meta charset="UTF-8" />
	<meta name="viewport"
		content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
	<title>主体标注</title>
	<link rel="stylesheet" href="./styles/pointCheck.css">
	<link rel="stylesheet" href="./js/leaflet/leaflet.css">
	<script type="text/javascript" src="./js/leaflet/leaflet.js"></script>
</head>

<body onload="initMap()">
	<div class="bottom-content">
		<div class="point-item">
			<span class="point-text">搜索地点</span>
			<input class="point-input" id="companyName" placeholder="请输入搜索地点" />
			<button class="search-btn" onclick="startSearch()">搜索</button>
		</div>
		<div class="point-item">
			<img src="img/point4.png" class="point-icon" />
			<span class="point-text">点击重新获取当前设备位置</span>
		</div>
		<div class="point-item">
			<img src="img/yuandian.png" class="point-icon" />
			<span class="point-text">当前设备GPS坐标位置</span>
		</div>
		<div class="point-item">
			<img src="img/point.png" class="point-icon" style="width: 16px;margin-left: 5px;" />
			<span class="point-text" style="margin-left: 10px;">企业坐标位置</span>
		</div>

		<!-- 屏幕中心获取企业位置 -->
		<div class="bottom-btn">
			<!-- <button onclick="pointConfirm()" class="confirm-btn" type="buttom" style="color: #ffffff;"> 确定</button> -->
			<button onclick="bacPage()" class="cancell-btn" type="buttom">返回</button>
		</div>
	</div>
	<!-- 搜索结果 -->
	<div class="search-content" id="searchContent">
		<div class="search-list" id="content" onscroll="checkScroll(this)"></div>
		<div class="bottom-btn" style="">
			<button onclick="closeSearch()" class="cancell-btn" type="buttom">关闭</button>
		</div>
	</div>
	<div style="position: absolute;z-index:2" id="map"></div>
	<div class="point" onclick="getCurrentPoint()">
		<img src="img/point4.png" style="width: 40px;height: 40px;" />
	</div>
</body>
<script type="text/javascript" src="./js/jquery.min.js"></script>
<script type="text/javascript" src="./js/uni.webview.1.5.6.js"></script>
<script type="text/javascript" src="./js/map-util.js"></script>
<script type="text/javascript">
	var map = null;// 地图实例
	var pageReady = false; //map加载状态
	var currentMarker = null; //当前定位
	var companyMarker = null; //企业位置标记
	var markers = []; // 存储搜索结果标记
	var lastPage = false;//搜索结果是否最后一页

	var int = null;
	document.addEventListener('UniAppJSBridgeReady', function () {
		console.log('UniAppJSBridgeReady环境已准备完成：');
		int = setInterval(function () {
			//页面完成,获取当前位置  
			if (pageReady) {
				clearInterval(int);
				getCurrentPoint();
			}
		}, 500)
	});

	//初始化地图
	function initMap() {
		//获取参数
		var params = getUrlParams();
		var lng = params.lng;
		var lat = params.lat;

		// 初始化Leaflet地图
		map = L.map('map', {
			center: [39.908, 116.397], // 默认中心点（北京）
			zoom: 12,
			zoomControl: false
		});

		// 添加高德地图瓦片图层
		L.tileLayer('https://wprd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}', {
			subdomains: ['1', '2', '3', '4'],
			attribution: '&copy; 高德地图'
		}).addTo(map);

		if (lng != null && lng != '' && lng != 'undefined' && lat != null && lat != 'undefined' && lat != '') {
			lng = parseFloat(lng);
			lat = parseFloat(lat);

			// 将WGS84坐标转换为GCJ02坐标（高德地图使用的坐标系）
			var gcj02 = wgs84togcj02(lng, lat);

			//企业当前定位
			map.setView([gcj02.lat, gcj02.lng], 12);

			//创建企业位置标注
			var companyIcon = L.icon({
				iconUrl: "img/point.png",
				iconSize: [19, 27],
				iconAnchor: [9, 27]
			});

			companyMarker = L.marker([gcj02.lat, gcj02.lng], { icon: companyIcon }).addTo(map);
		}

		pageReady = true;
	}

	/**
	 * 提交地图标注信息
	 */
	function pointConfirm() {
		uni.postMessage({
			data: { type: 'back' }
		})
	}

	//-----------------------------搜索-start-----------------------------
	/**
	 * 点击搜索按钮
	 */
	function startSearch() {
		//清空历史搜索结果
		var searchContent = document.getElementById("content");
		searchContent.innerHTML = '';

		// 清除之前的搜索标记
		markers.forEach(function (marker) {
			map.removeLayer(marker);
		});
		markers = [];

		lastPage = false;
		var searchQuery = document.getElementById('companyName').value;
		if (!searchQuery) {
			uni.postMessage({
				data: { type: 'toast', message: '请输入搜索关键词', icon: 'none' }
			});
			return;
		}

		$.ajax({
			url: 'http://116.130.215.195:8188/base/queryPOIByName',
			type: 'GET',
			dataType: 'json',
			data: {
				name: searchQuery
			},
			success: function (result) {
				if (result.code == 0) {
					if (result.data && result.data.length > 0) {
						// 转换结果为所需格式
						var pois = result.data.map(function (item) {
							return {
								name: item.name,
								lonlat: item.longitude + "," + item.latitude,
								address: `${item.city}${item.region}`
							};
						});

						// 使用现有方法处理结果
						localSearchResult({ getPois: function () { return pois; } });
					} else {
						uni.postMessage({
							data: { type: 'toast', message: result.message, icon: 'none' }
						});
					}
				}
			},
			error: function (error) {
				uni.postMessage({
					data: { type: 'toast', message: '搜索请求失败', icon: 'error' }
				});
				console.error('搜索失败:', error);
			}
		});

		var searchBox = document.getElementById("searchContent");
		searchBox.style.display = 'block';
	}

	/**
	 * 地图关键字搜索结果
	 */
	function localSearchResult(result) {
		if (result.getPois && result.getPois()) {
			var searchContent = document.getElementById("content");
			var content = "";
			var pois = result.getPois();
			if (lastPage) {
				//最后一页了
				return;
			}
			for (var i = 0; i < pois.length; i++) {
				var lnglatArr = pois[i].lonlat.split(",");

				content = content + `<div class="search-item" onclick="selectCompany('${pois[i].lonlat}')" >
							<span class="search-name">${pois[i].name}</span>
							<span class="search-address">坐标:${pois[i].lonlat}</span>
							<span class="search-address">地址:${pois[i].address}</span>
						</div>`;

				// 在地图上添加标记
				var marker = L.marker([lnglatArr[1], lnglatArr[0]], {
					icon: L.icon({
						iconUrl: "img/point.png",
						iconSize: [19, 27],
						iconAnchor: [9, 27]
					})
				}).addTo(map);
				markers.push(marker);
			}
			searchContent.innerHTML = searchContent.innerHTML + content;
			if (pois.length < 10) {
				lastPage = true;
			}
		}
	}

	/**
	 * 选中某个企业之后中心移动到此位置
	 * @param {Object} lngLat
	 */
	function selectCompany(lngLat) {
		var searchBox = document.getElementById("searchContent");
		searchBox.style.display = 'none';
		if (lngLat != null && lngLat != '') {
			var lngLatArr = lngLat.split(',');
			//移动到这个位置 (已经是GCJ02坐标，无需再转换)
			map.setView([lngLatArr[1], lngLatArr[0]], 12);

			//添加marker
			if (companyMarker != null) {
				//清除之前的marker
				map.removeLayer(companyMarker);
			}

			//创建企业位置标注
			var companyIcon = L.icon({
				iconUrl: "img/point.png",
				iconSize: [19, 27],
				iconAnchor: [9, 27]
			});

			companyMarker = L.marker([lngLatArr[1], lngLatArr[0]], { icon: companyIcon }).addTo(map);
			return;
		}
		uni.postMessage({
			data: { type: 'toast', message: '没有坐标信息!', icon: 'error' }
		});
	}

	/**
	 * 关闭搜索
	 */
	function closeSearch() {
		var searchBox = document.getElementById("searchContent");
		searchBox.style.display = 'none';
	}

	function checkScroll(that) {
		var content = document.getElementById("content");
		if (that.scrollTop + that.clientHeight >= that.scrollHeight - 30) {
			// 加载下一页内容的操作
			// 这里需要实现实际的翻页功能
		}
	}

	//---------------------------搜索end----------------------------

	/**
	 * 获取当前位置
	 */
	function getCurrentPoint() {
		uni.postMessage({
			data: { type: 'getCurrentPoint' }
		})
	}

	function currentPointCallback(lngLat) {
		var lngLatArr = lngLat.split(",");
		var lng = parseFloat(lngLatArr[0]);
		var lat = parseFloat(lngLatArr[1]);

		// 将WGS84坐标转换为GCJ02坐标（高德地图使用的坐标系）
		var gcj02 = wgs84togcj02(lng, lat);

		//创建标注对象
		var icon2 = L.icon({
			iconUrl: "img/yuandian.png",
			iconSize: [19, 19],
			iconAnchor: [9, 9]
		});

		if (currentMarker == null) {
			currentMarker = L.marker([gcj02.lat, gcj02.lng], { icon: icon2 }).addTo(map);
		} else {
			currentMarker.setLatLng([gcj02.lat, gcj02.lng]);
		}

		//移动到这个位置 
		map.setView([gcj02.lat, gcj02.lng], 12);
	}

	//获取链接参数
	function getUrlParams() {
		var url = window.location.href;
		var params = url.split('?')[1];
		var paramsObj = {};

		if (params) {
			var paramArray = params.split('&');
			paramArray.forEach(function (param) {
				var paramSplit = param.split('=');
				paramsObj[paramSplit[0]] = paramSplit[1];
			});
		}
		return paramsObj;
	}

	function bacPage() {
		console.log('返回')
		uni.postMessage({
			data: { type: 'back' }
		})
	}
</script>

</html>